package pro4;

import javax.servlet.*;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/Ans4/EditProductServlet")
@MultipartConfig
public class EditProductServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        String id = request.getParameter("id");
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        int stock = Integer.parseInt(request.getParameter("stock"));

        ProductDAO dao = null;
        try {
            dao = new ProductDAO();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        Product product = null;
        try {
            product = dao.getProductById(id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        if (product == null) {
            response.sendRedirect("product_management.jsp");
            return;
        }

        // 更新字段
        product.setName(name);
        product.setPrice(price);
        product.setStock(stock);

        Part filePart = request.getPart("image");
        if (filePart != null && filePart.getSize() > 0) {
            String imageFileName = extractFileName(filePart);
            String uploadPath = getServletContext().getRealPath("") + File.separator + "images";
            String imageUrl = "images/" + imageFileName;

            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) uploadDir.mkdirs();

            filePart.write(uploadPath + File.separator + imageFileName);
            product.setImageUrl(imageUrl);
        }

        try {
            dao.updateProduct(product);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        response.sendRedirect("product_management.jsp");
    }

    private String extractFileName(Part part) {
        String contentDisp = part.getHeader("content-disposition");
        for (String content : contentDisp.split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(content.indexOf("=") + 2, content.length() - 1);
            }
        }
        return "";
    }
}

